import React, { FunctionComponent, useState } from 'react';
import { graphql } from 'react-relay';
import useApiMutation from '../../../../utils/hooks/useApiMutation';
import { malwareEditionOverviewFocus } from './MalwareEditionOverview';
import { QueryRenderer } from '../../../../relay/environment';
import { MalwareEditionContainerQuery$data } from './__generated__/MalwareEditionContainerQuery.graphql';
import Drawer, { DrawerControlledDialType, DrawerVariant } from '../../common/drawer/Drawer';
import { useFormatter } from '../../../../components/i18n';
import Loader, { LoaderVariant } from '../../../../components/Loader';
import MalwareEditionContainer from './MalwareEditionContainer';
import useHelper from '../../../../utils/hooks/useHelper';

export const malwareEditionQuery = graphql`
  query MalwareEditionContainerQuery($id: String!) {
    malware(id: $id) {
      ...MalwareEditionContainer_malware
      editContext {
        name
        focusOn
      }
    }
  }
`;

interface MalwareEditionProps {
  malwareId: string;
  controlledDial?: DrawerControlledDialType;
}

const MalwareEdition: FunctionComponent<MalwareEditionProps> = ({
  malwareId,
  controlledDial,
}) => {
  const { t_i18n } = useFormatter();
  const { isFeatureEnable } = useHelper();
  const isFABReplaced = isFeatureEnable('FAB_REPLACEMENT');
  const [open, setOpen] = useState<boolean>(false);
  const [commit] = useApiMutation(malwareEditionOverviewFocus);

  const handleClose = () => {
    commit({
      variables: {
        id: malwareId,
        input: { focusOn: '' },
      },
    });
    setOpen(false);
  };

  return (
    <QueryRenderer
      query={malwareEditionQuery}
      variables={{ id: malwareId }}
      render={({ props }: { props: MalwareEditionContainerQuery$data }) => {
        if (props) {
          return (
            <Drawer
              title={t_i18n('Update a malware')}
              open={open}
              onClose={handleClose}
              variant={!isFABReplaced ? DrawerVariant.update : undefined}
              context={props.malware?.editContext}
              controlledDial={isFABReplaced ? controlledDial : undefined}
            >
              <MalwareEditionContainer malware={props.malware} handleClose={handleClose} />
            </Drawer>
          );
        }
        return (
          <Drawer
            title={t_i18n('Update a malware')}
            open={open}
          >
            <Loader variant={LoaderVariant.inElement} />
          </Drawer>
        );
      }}
    />
  );
};

export default MalwareEdition;
